#include<vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
    TreeNode* flattenHelper(TreeNode* root) {
        if (root == NULL) return root;
        auto left = flattenHelper(root->left);
        auto right = flattenHelper(root->right);
        if (left != NULL) {
            left->right = root->right;
            root->right = root->left;
            root->left = NULL;
        }
        return right != NULL ? right : (left != NULL ? left : root);
    }

public:
    void flatten(TreeNode* root) {
        flattenHelper(root);
    }
};